package com.yunpi.yunpicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.yunpi.yunpicturebackend.exception.BusinessException;
import com.yunpi.yunpicturebackend.exception.ErrorCode;
import com.yunpi.yunpicturebackend.exception.ThrowUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

/**
 * url上传
 */
@Service
public class UrlPictureUpload extends PictureUploadTmplate {
    @Override
    protected void processFile(Object inputSource, File file) throws IOException {
        String fileUrl = (String) inputSource;
        HttpUtil.downloadFile(fileUrl,file);
    }

    @Override
    protected String getOriginalFilename(Object inputSource) {
        String fileUrl = (String) inputSource;
        return FileUtil.mainName(fileUrl);
    }

    @Override
    protected void voidPicture(Object inputSource) {
        String fileUrl = (String) inputSource;
        //检验非空
        ThrowUtils.throwIf(fileUrl==null, ErrorCode.PARAMS_ERROR,"文件地址为空");
        //检验url
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件地址不正确");
        }
        //检验url协议
        ThrowUtils.throwIf(!fileUrl.startsWith("http://") && !fileUrl.startsWith("https://"),
                ErrorCode.PARAMS_ERROR,"仅支持HTTP协议或HTTPS协议");

        //发送HEAD请求验证文件是否存在
        HttpResponse httpResponse =null;
        try{
            httpResponse= HttpUtil.createRequest(Method.HEAD,fileUrl)
                    .execute();
            //未正常，无须执行其他判断
            if(httpResponse.getStatus() != HttpStatus.HTTP_OK){
                return;
            }
            //文件存在，文件类型校验
            String contentType = httpResponse.header("Content-Type");
            //不为空，才校验是否合法
            if(StrUtil.isNotBlank(contentType)){
                //允许上传文件的格式列表
                final List<String> ALLOW_FORMAT_LIST = Arrays.asList("image/jpeg","image/png","image/jpg","image/webp");
                ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(contentType.toLowerCase()),ErrorCode.PARAMS_ERROR,"文件类型错误");
            }
            //文件存在，文件大小校验
            String contentLengthStr = httpResponse.header("Content-Length");
            if (StrUtil.isNotBlank(contentLengthStr)){
                try {
                    long contentLength = Long.parseLong(contentLengthStr);
                    final long ONE_M =1024*1024;
                    ThrowUtils.throwIf(contentLength>2*ONE_M,ErrorCode.PARAMS_ERROR,"文件大小不能超过2MB");
                }catch (NumberFormatException e){
                    throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件大小格式异常");
                }

            }

        }finally {
            //释放资源
            if (httpResponse!=null){
                httpResponse.close();
            }

        }{

        }
    }
}
